package com.shxzz.easy12306.services.pay.handler.ali;

import cn.hutool.core.text.CharSequenceUtil;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.domain.AlipayTradePagePayModel;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.response.AlipayTradePagePayResponse;
import com.shxzz.easy12306.framework.starter.convention.exceptions.ServiceException;
import com.shxzz.easy12306.services.pay.common.enums.PayChannelEnum;
import com.shxzz.easy12306.services.pay.common.enums.PayTradeTypeEnum;
import com.shxzz.easy12306.services.pay.config.AliPayProperties;
import com.shxzz.easy12306.services.pay.dto.ali.AliPayRequest;
import com.shxzz.easy12306.services.pay.dto.base.PayRequest;
import com.shxzz.easy12306.services.pay.dto.resp.PayResponse;
import com.shxzz.easy12306.services.pay.handler.base.PayHandler;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * @author shxzz
 * @create 2024-03-11-22:35
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class AliPayHandler implements PayHandler {

    private final AliPayProperties aliPayProperties;
    private final AlipayClient alipayClient;

    @Override
    public PayResponse pay(PayRequest payRequest) {
        AliPayRequest aliPayRequest = (AliPayRequest) payRequest;
        AlipayTradePagePayModel model = new AlipayTradePagePayModel();
        model.setOutTradeNo(aliPayRequest.getOrderSn());
        model.setTotalAmount(aliPayRequest.getTotalAmount().toString());
        model.setSubject(aliPayRequest.getSubject());
        model.setProductCode("FAST_INSTANT_TRADE_PAY");

        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        request.setNotifyUrl(aliPayProperties.getNotifyUrl());
        request.setBizModel(model);

        try {
            AlipayTradePagePayResponse response = alipayClient.pageExecute(request);
            log.info("发起支付宝支付，订单号：{}，订单金额：{}",
                    aliPayRequest.getOrderSn(),
                    aliPayRequest.getTotalAmount()
            );
            if (!response.isSuccess()) {
                throw new ServiceException("调用支付宝发起支付异常");
            }
            return new PayResponse(
                    CharSequenceUtil.replace(
                            CharSequenceUtil.replace(response.getBody(), "\"", "'"),
                            "\n",
                            "")
            );
        } catch (AlipayApiException ex) {
            throw new ServiceException("调用支付宝支付异常");
        }
    }

    @Override
    public PayResponse executeResp(PayRequest requestParam) {
        return pay(requestParam);
    }

    @Override
    public String mark() {
        return PayChannelEnum.ALI_PAY.getName() + "_" + PayTradeTypeEnum.NATIVE.name();
    }
}
